package org.harlov.testsys.db;

import java.awt.Checkbox;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;

import org.harlov.testsys.loger;
import org.harlov.testsys.db.suppdata.ans_struct;
import org.harlov.testsys.db.suppdata.quest_struct;
import org.harlov.testsys.db.suppdata.test_log_struct;
import org.harlov.testsys.views.gui_factory;


public class test_loger {
	
	private static DefaultListModel quests_views; //Список вопросов для отображения
	private static ArrayList<quest_struct> quests_list_student; //Список вопросов в quest_struct,для обработки 
	private static ArrayList<ans_struct> stud_ans; //Ответы студента
	private static ArrayList<Integer> anslog_ids;
	
	private static ArrayList<test_log_struct> tests_logs;
	private static DefaultListModel tests_logs_views;
	private static int cur_test ;
	private static int cur_student;
	private static int cur_quest;
	private static int cur_list_test;
	private static int cur_log_id = 0;
	private static db_main DB;

	
	private static String[] t_ans ;
	private static String[] f_ans ;
	
	public test_loger (db_main _DB) {
		quests_views = new DefaultListModel();
		tests_logs_views = new DefaultListModel();
		tests_logs = new ArrayList<test_log_struct>();
		DB = _DB;
		
		stud_ans = new ArrayList<ans_struct>();
		anslog_ids = new ArrayList<Integer>();
		
	}
	
	
	
	public static DefaultListModel getQuestsViewForStudents() {
		
		quests_views.clear();
		
		
		for (int i = 0; i<quests_list_student.size(); i++) {
			quest_struct temp = quests_list_student.get(i);
			quests_views.addElement(temp.getId());
		}
		return quests_views;		
	}	
	
	public static ArrayList<quest_struct> getQuestsForStudents(int test,int list_test) {
		quests_list_student = quests.getQuests(test);
		System.out.println("Quests list size>"+quests_list_student.size());
		Collections.shuffle(quests_list_student);
		System.out.println("Quests list for student size :>"+tests.getTestQCount(list_test-1));
		ArrayList<quest_struct> temp_list = new ArrayList<quest_struct> ();
		if (tests.getTestQCount(list_test-1)<quests_list_student.size())
		for (int i = tests.getTestQCount(list_test-1);i<quests_list_student.size();i++) {
			temp_list.add(quests_list_student.get(i));			
		}
		System.out.println("Removed elements:>"+temp_list.size());
		quests_list_student.removeAll(temp_list);
		
			
		return quests_list_student;
	}
	public static void drawAns(gui_factory gFactory,int quest_id) {  //Получение ответов и создание чекбоксов 
		cur_quest = quest_id -1;
		quest_struct temp_quest = quests_list_student.get(cur_quest);
		t_ans = temp_quest.getTAns();
		f_ans = temp_quest.getFAns();
		ans_struct temp_ans_cur = stud_ans.get(cur_quest);
		gFactory.removeAllCheckBoxs();
		ArrayList<String[]> out_list = new ArrayList<String[]>();
		int jk = 0 ;
		for (String tans:t_ans) {
			String[] temp_s = new String[4];
			temp_s[0] = "t";
			temp_s[1] = tans;
			temp_s[2] = String.valueOf(temp_ans_cur.getValT(jk));
			temp_s[3] = String.valueOf(jk);
			out_list.add(temp_s);
			jk++;
		}
		jk=0;
		for (String fans:f_ans) {
			String[] temp_s = new String[4];
			temp_s[0] = "f";
			temp_s[1] = fans;
			temp_s[2] = String.valueOf(temp_ans_cur.getValF(jk));
			temp_s[3] = String.valueOf(jk);
			out_list.add(temp_s);
			jk++;
		}
		Collections.shuffle(out_list);
		for (int i =0;i<out_list.size();i++) {
			Checkbox temp_check;
			String[] temp_ans = out_list.get(i);
			if (temp_ans[0] == "t") {
				gFactory.newCheckBox("t_"+temp_ans[3]+"_"+cur_quest,temp_ans[1],Boolean.valueOf(temp_ans[2]));
			}
			if (temp_ans[0] == "f") {
				gFactory.newCheckBox("f_"+temp_ans[3]+"_"+cur_quest, temp_ans[1],Boolean.valueOf(temp_ans[2]));
			}
			
		}
		System.out.println("Ansewrs drawed on stest_form");
	}
	
	public static void CheckChange(JCheckBox temp) {  //При отметке какого-либо чекбокса
			
	
			ans_struct temp_ans = stud_ans.get(cur_quest);
			
			String[] ans_name = temp.getName().split("_");
			System.out.println("Изменение состояния CheckBox>"+" "+temp.getName());
					
			if (ans_name[0].compareTo("f")==0) {
				temp_ans.setValF(Integer.parseInt(ans_name[1]),temp.isSelected());
			}
			else
			if (ans_name[0].compareTo("t")==0) { 
				temp_ans.setValT(Integer.parseInt(ans_name[1]),temp.isSelected());
			}
			saveAns();
			
		
	}

	public static String getQuestText(int quest_id) {
		quest_struct temp_quest = quests_list_student.get(quest_id-1);
		return temp_quest.getText();
	}
	
	public static void StartNewTest(int _test,int _list_test,int _student) {  //Старт нового теста
		cur_test = _test;
		cur_student = _student;
		cur_list_test = _list_test;
		
		try {
			java.util.Date temp_dt = new Date();
			Timestamp temp_date = new Timestamp(temp_dt.getTime());
			ResultSet res = DB.makeReq("INSERT INTO tests_log (test_id,student_id,complete,p_date) VALUES('"+cur_test+"','"+cur_student+"','false','"+ temp_date+"') RETURNING log_id");
			if (res.next()) cur_log_id = res.getInt("log_id");
			
			getQuestsForStudents(cur_test,cur_list_test);
			stud_ans.clear();
			
			for (int i=0;i<quests_list_student.size();i++) {
				quest_struct temp_struct = quests_list_student.get(i); //Получаем вопрос
				ans_struct temp_ans = new ans_struct( temp_struct.getFAns().length,temp_struct.getTAns().length); //Создаем для него маску ответов студентов,и помещяем в список
				stud_ans.add(temp_ans);
				anslog_ids.add(ans_log.addAns(cur_log_id, temp_struct.getId()));
			}
			
			
		} catch (SQLException e) {loger.add("StartNewTest>"+e.getMessage(), null, 1);}
	}
	
	public static void endTest() {
		try {
			DB.makeUp("UPDATE tests_log SET complete='TRUE' WHERE log_id="+cur_log_id);
		} catch (SQLException e) {loger.add(e.getMessage(), null, 1);}
	}

	public static int getResultForStud() {
		int r_count = 0;
		for (ans_struct temp:stud_ans) if (temp.isRight()) r_count++;  
		return r_count;
			
	}


	public static void saveAns() {
		ans_struct temp_ans = stud_ans.get(cur_quest);
		ans_log.UpAns(anslog_ids.get(cur_quest),temp_ans.getValsF(),temp_ans.getValsT());
	}
	
	
	public static int getLogIdByList(int ind) {
		if (ind>-1)	return tests_logs.get(ind).getLogId();
		else return -1;
	}
	
	public static DefaultListModel getStudentsLogsView(int stud_id) {
		tests_logs_views.clear();
		getStudentsLogs(stud_id);
		for (test_log_struct temp:tests_logs) {
			tests_logs_views.addElement(temp.getLogId()+" Дата прохождения>"+temp.getDate());
		}
		return tests_logs_views;
	}
	
	public static ArrayList<test_log_struct> getStudentsLogs(int stud_id) {
		tests_logs.clear();
		try {
			ResultSet res = DB.makeReq("SELECT * FROM tests_log WHERE student_id = '"+stud_id+"' ORDER BY p_date DESC");
			while (res.next()) {
				tests_logs.add(new test_log_struct(res.getInt("log_id"),res.getInt("test_id"),res.getInt("student_id"),res.getBoolean("complete"),res.getTimestamp("p_date")));
				
			}
		}
		catch (SQLException e) {loger.add(e.getMessage(), null, 1);}
		return tests_logs;
		
	}
	
	
}
